const fs = require('fs-extra')
const path = require('path')
const parser = require('@babel/parser').parse
const traverse = require('@babel/traverse').default
const generate = require('@babel/generator').default
const t = require('@babel/types')

// 要添加的新路由数据
const newRoutes = [
  {
    path: '/NewComponent',
    name: '/NewComponent',
    component: `() => import('@projects/NewComponent/index.vue')`
  }
]

// 读取目标文件
const filePath = path.join(__dirname, '../../src/router/index.ts')
const code = fs.readFileSync(filePath, 'utf-8')

// 解析为 AST
const ast = parser(code, {
  sourceType: 'module',
  plugins: ['typescript', 'dynamicImport']
})

// 遍历 AST 查找目标数组
traverse(ast, {
  VariableDeclarator(path) {
    if (t.isIdentifier(path.node.id, { name: 'appRoutes' }) && t.isArrayExpression(path.node.init)) {
      // 添加新路由项
      newRoutes.forEach((route) => {
        // 手动创建动态导入 AST 节点
        const importExpression = t.callExpression(
          t.import(),
          [t.stringLiteral(route.component.replace(/^.+?\(|\)$/g, '').replace(/['"]/g, ''))] // 去掉多余的引号
        )

        const arrowFunction = t.arrowFunctionExpression([], importExpression)

        // 创建路由对象的属性
        const Path = t.objectProperty(t.identifier('path'), t.stringLiteral(route.path))
        const Component = t.objectProperty(t.identifier('component'), arrowFunction)
        const properties = [Path, Component]

        // 将新路由对象添加到 appRoutes 数组中
        path.node.init.elements.push(t.objectExpression(properties))
      })
    }
  }
})

// 生成新代码
const output = generate(ast, {
  retainLines: true,
  comments: true,
  compact: false
}).code

// 写回文件
fs.writeFileSync(filePath, output)
